/**
 * 拖动侧边bar
 * @author SPY
 * @url 语雀:https://www.yuque.com/study365
 */

import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Resizable } from 're-resizable';
import styles from './DragSideBar.less';

const DragSideBar = ({
  showSlot = <div className={styles.showSlot}>展示区域默认数据</div>,
  dragSlot = <div className={styles.dragSlot}>可拖动区域默认数据</div>,
  handleSlot = <div className={styles.handleSlot}>手柄</div>,
  defaultHeight = 200,
  defaultWidth = 200,
  width: widthValue,
  height: heightValue,
  dragPosition = 'left',
  onChange,
}) => {
  const [width, setWidth] = useState(() =>
    widthValue ? widthValue : defaultWidth,
  );
  const [height, setHeight] = useState(() =>
    heightValue ? heightValue : defaultHeight,
  );

  const newWidth = typeof widthValue !== 'undefined' ? widthValue : width; // 受控宽
  const newHeight = typeof heightValue !== 'undefined' ? heightValue : height; // 受控高

  return (
    <div style={{ width: '100%', display: 'flex', overflow: 'hidden', height }}>
      {dragPosition === 'right' && (
        <>
          {showSlot}
          {handleSlot}
        </>
      )}
      <Resizable
        size={{
          width: newWidth,
          height: newHeight,
        }}
        className={styles.resizable}
        minWidth={0}
        enable={{
          left: dragPosition === 'right',
          right: dragPosition === 'left',
        }}
        onResizeStop={(e, direction, ref, d) => {
          const nWidth = newWidth + d.width;
          const nHeight = newHeight + d.height;
          setWidth(nWidth);
          setHeight(nHeight);
          if (typeof onChange === 'function') {
            onChange(nWidth, nHeight);
          }
        }}
      >
        {dragSlot}
      </Resizable>
      {dragPosition === 'left' && (
        <>
          {handleSlot}
          {showSlot}
        </>
      )}
    </div>
  );
};

DragSideBar.propTypes = {
  showSlot: PropTypes.node, // 展示插槽，注意展示插槽的样式宽度必须设置100%
  dragSlot: PropTypes.node, // 可拖动插槽
  handleSlot: PropTypes.node, // 手柄插槽
  defaultHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), // 拖动区域默认高度
  defaultWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), // 拖动区域默认宽度
  width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), // 受控拖动区域宽度
  height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), // 受控拖动区域高度
  dragPosition: PropTypes.oneOf(['left', 'right']), // 拖动位置在左侧或者右侧
  onChange: PropTypes.func, //
};

export default DragSideBar;
